<template>
  <q-page class="q-pa-md" v-loading="loading">
    <div style="position: relative;">
      <q-breadcrumbs class="q-mb-md" style="height:50px;line-height: 40px; border-bottom: 1px dashed #ccc;">
        <el-icon style="cursor: pointer;" @click="router.go(-1)">
          <ArrowLeft />
        </el-icon>
        <q-breadcrumbs-el label="数据概览" />
      </q-breadcrumbs>
      <div class="row q-gutter-lg justify-between topData">
        <div class="col ">
          <div class="title" style="text-align: left;">总览</div>
          <div>ID:{{ tableData.id }}</div>
          <div>实验名称：{{ tableData.name }}</div>
          <div v-if="tableData.description">说明：{{ tableData.description }}</div>
          <div v-if="tableData.create_at">创建时间：{{ tableData.create_at }}</div>
          <div v-if="tableData.update_at">更新时间：{{ tableData.update_at }}</div>
        </div>
        <div class="col ">
          <div class="title" style="text-align: left;">预览图</div>
          <div class="toCanvas">
            <el-image v-if="tableData.icon_url" style="width: 100%; max-height:200px;" :src="tableData.icon_url"
              fit="contain" />
            <el-icon @click="toCanvas()">
              <Edit />
            </el-icon>
          </div>
        </div>
        <div class="col ">
          <div class="title" style="text-align: left;">时间轴</div>
          <div v-if="experimentData.results.length > 0">
            <chart-line :chartOption="chartOption2" :chartSize="chastSize2" ref="chartRef"></chart-line>
          </div>
          <div v-else>暂无数据</div>
        </div>
      </div>
      <div class="bottomData">
        <div class="title">最近的工作<i>显示最近3个月内操作过的实验</i></div>
        <div class="secondTitle">
          <i>实验</i>
          <div></div>
        </div>
        <el-table :data="experimentData.results" style="width: 100%">
          <el-table-column prop="id" label="ID" />
          <el-table-column prop="name" label="实验名称">
            <template #default="scope">
              <el-button link type="primary" @click="toDetailPage(scope.row.workflow_id, scope.row.id)">{{ scope.row.name
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" />
          <el-table-column prop="status" label="运行状态">
            <template #default="scope">
              <el-tag :type="operatorRunState(scope.row.status)" class="mx-1" effect="plain" round>
                {{ stateText(operatorRunState(scope.row.status))  }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="version" label="工作流版本" />
          <el-table-column prop="create_time" label="创建时间" />
          <el-table-column label="运行时长">
            <template #default="scope">{{ runTime(scope.row) }}</template>
          </el-table-column>
          <template #empty>
            <div class="noData">暂无数据</div>
          </template>
        </el-table>
        <div class="row" style="justify-content:flex-end;" v-if="experimentData.results.length > 0">
          <el-pagination background layout="prev, pager, next" :total="experimentData.count" style="margin: 10px 0 ;"
            page-size="10" :current-page="pageData.page" @current-change="changePage" />
        </div>

      </div>
    </div>
  </q-page>
</template>

<script setup lang="ts">
import { ref, shallowRef, nextTick, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { getWorkflowsDetail, getExperiments } from 'src/api/designerTool'
import { designerStore } from 'src/stores/designerTool/designerTool'
import { operatorRunState, secondToTime,stateText } from 'src/utils/designerTool/toole'
import chartLine from 'src/components/chartLine.vue';
// import boxLoading from 'src/components/boxLoading.vue';
const router = useRouter()
const store = designerStore()
const projectId = router.currentRoute.value.params.project_id
const loading = ref(false)
const chartRef = ref<any>(null)
const bottomTabelData = shallowRef({
  count: 0,
  results: <any>[]
})
const tableData = shallowRef({
  id: '',
  name: '',
  data_title: '',
  create_at: '',
  update_at: '',
  status: '',
  description: '',
  version_summary: {},
  is_random: false,
  icon_url: ''
})
const chartDataArr = ref(<any>[])

const pageData = ref({
  page: 1
})
const experimentData = ref({
  count: 0,
  results: <any>[]
})
const chastSize2 = reactive({
  width: '90%',
  height: "255px"
})

const chartOption2 = reactive({
  tooltip: {
    axisPointer: {
      type: 'shadow', //默认为line，line直线，cross十字准星，shadow阴影
      crossStyle: {
        color: '#fff'
      }
    },
    trigger: 'axis',
    formatter: function (params: any) {
      let res = `
        <div>
          <span>${'运行时长：' + params[0].value + '秒'}</span>
        </div>
      `
      return '实验名称：' + params[0].axisValue + res
    }
  },
  grid: {
    left: '1%',
    right: '1%',
    bottom: '5%',
    top: '8%',
    containLabel: true
  },

  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      show: false
    },
    axisTick: {
      show: false
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: '{value}秒'
    }
  },
  series: [
    {
      data: [],
      color: '#5edf5e',
      type: 'bar'
    }
  ]
})

// 切换页
function changePage(currentPage: any) {
  pageData.value.page = currentPage
  // setData(chooseNumber.value)
  getExperimentsFun()
}
function toCanvas() {
  store.LEFT_TABS_STATE(true)
  store.EXOERIMENTS_ID({})
  let routeData = router.resolve({ name: 'canvas-index' })
  if (routeData) {
    nextTick(() => {
      window.open(routeData.href, '_blank')
    })
  }
}
getDetailData()
function getDetailData() {
  loading.value = true
  getWorkflowsDetail(projectId, store.workflow_id).then((res: any) => {
    tableData.value = res.data
    loading.value = false
    store.TEMPLATE_ID(res.data.template_id)
    getExperimentsFun()
  }).catch(error => {
    console.log(error)
  })
}

function getExperimentsFun() {
  let obj = {
    page: pageData.value.page
  }
  getExperiments(projectId, store.template_id, obj).then((res: any) => {
    experimentData.value = res.data
    if (experimentData.value.results.length > 0) {
      chartsData()
    }
  }).catch(error => {
    console.log(error)
  })
}

// 实验时间轴数据处理
function chartsData() {
  chartDataArr.value = []
  experimentData.value.results.forEach((item: any) => {
    if (item.finish_time != undefined && item.finish_time.length > 1) {
      let resultTime = Date.parse(item.finish_time) / 1000 - Date.parse(item.start_time) / 1000
      let obj = {
        name: item.name,
        run_time: resultTime
      }
      chartDataArr.value.push(obj)
    }
  })
  nextTick(() => {
    chartOption2.series[0].data = chartDataArr.value.map((item: any) => {
      return item.run_time;
    });
    chartOption2.xAxis.data = chartDataArr.value.map((item: any) => {
      return item.name;
    })
    chartRef.value.init()
  })
}

function toDetailPage(workflowId: number, experiments: number) {
  // store.SET_WORKFLOW_ID(workflowId)
  // store.SET_INSTANCE_ID(experiments)
  store.instance_id = experiments
  let obj = {
    workflow_id: workflowId,
    id: experiments
  }
  store.EXOERIMENTS_ID(obj)
  router.push({ name: 'designer-tool-experiments', query: { project_id: projectId } })
}
const runTime = (row: any) => {
  if (row.create_time != undefined) {
    let dateObj = {
      start_time: Date.parse(row.start_time) / 1000
    }
    if (row.finish_time != undefined) {
      dateObj.end_time = Date.parse(row.finish_time) / 1000
    }
    return secondToTime(dateObj)
  }
}


</script>

<style scoped lang="scss">
.topData {
  width: 100%;
  margin-bottom: 20px;
  color: #101010;

  .title {
    font-size: 18px;
    margin-bottom: 15px;
    font-weight: bold;
  }

  .col {
    padding: 20px 15px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    background: white;
    min-height: 200px;

    &:nth-child(1) {
      div {
        margin-bottom: 5px;
      }
    }
  }

  .rightBox {
    width: 100%;
    display: flex;

    &::v-deep .el-switch.is-disabled .el-switch__core,
    .el-switch.is-disabled .el-switch__label {
      cursor: initial !important;
    }
  }

  .errorState {
    cursor: not-allowed;
    opacity: 0.7;
    filter: grayscale(1);
  }

  .toCanvas {
    font-size: 18px;
    position: relative;
    transition: all .2s;
    min-height: 200px;

    &:hover {
      background: white;
      filter: contrast(0.8);

      .el-icon {
        opacity: 1;
      }
    }

    .el-icon {
      font-size: 25px;
      position: absolute;
      left: 48%;
      top: 44%;
      cursor: pointer;
      opacity: 0;

      &:hover {
        color: #3D5CE4;
      }
    }

    & ::v-deep .el-image__inner {
      height: 200px;
    }
  }
}

.bottomData {
  width: calc(100% - 24px);
  padding: 0 10px;
  border-radius: 3px;
  border: 1px solid #e0e0e0;
  min-height: 350px;
  position: relative;

  .title {
    margin: 10px 0 5px 0;
    color: #101010;
    font-size: 18px;
    margin-bottom: 15px;
    font-weight: bold;

    i {
      font-size: 12px;
      color: #bdbdbd;
      font-style: initial;
      margin-left: 5px;
      margin-bottom: -10px;
    }
  }

  .secondTitle {
    height: 26px;
    color: #3D5CE4;
    font-weight: bold;
    border-bottom: 2px solid #e7e6e6;
    margin-bottom: 5px;
    position: relative;

    i {
      font-style: initial;
      display: inline-block;
      border-bottom: 2px solid #3D5CE4;
      position: absolute;
      bottom: -2px;
    }
  }

  .el-col {
    margin-bottom: 20px;

    .el-image {
      height: 180px;
    }
  }

  .noDataBox {
    margin: 50px 0;
    text-align: center;
    font-size: 18px;
  }

  .col_box_5 {
    width: 20%;
    max-width: 20%;
  }
}
</style>
